<?php

namespace Apps\Manage\Controllers;

use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use PhalconPlus\Operator\GroupRight as OperatorGroupRight;
use Apps\Common\Models\BackendOperatorLog;
use Phalcon\Mvc\Controller;
use PhalconPlus\Operator\Identity as OperatorIdentity;
use PhalconPlus\Common\Util;
use Apps\Common\Libs\UploadPic;

class BaseController extends Controller
{
    /**
     * 每页现实数量
     * @var int
     */
    public $pageNavLimit = 20;
    /**
     * @var \PhalconPlus\Operator\Identity
     */
    public $operator;

    /**
     * @param \Phalcon\Mvc\Dispatcher|\Phalcon\Mvc\DispatcherInterface $dispatcher
     * @return bool
     */
    public function beforeExecuteRoute($dispatcher)
    {
        $this->operator = new OperatorIdentity();
        $this->operator->cookies = $this->cookies;
        $this->operator->load();
        // 判断登录
        $moduleConfig = $this->di->get('moduleConfig');
        $controllerName = $dispatcher->getControllerName();
        $actionName = $dispatcher->getActionName();
        if($controllerName == $moduleConfig->operator->login->controller && $actionName == $moduleConfig->operator->login->action)
        {
            return true;
        }
        if($this->operator->isLogin())
        {
            // 判断权限
            $result = OperatorGroupRight::verify($this->operator->group, $controllerName, $actionName, $dispatcher->getDI());
            // 权限不足，输出错误
            if(!$result) {
                $content = '';
                if($this->request->isAjax()) {
                    $resp = new ResponseResult();
                    $resp->sendError(ResponseResultStatus::RIGHT_VERIFY_FAIL, '权限不足!');
                    $content = $resp->getContent();
                } else {
                    $content = '访问权限不足！';
                }
                $this->view->disable();
                echo $content;
            }
            return $result;
        }

        if($this->request->isAjax()) {
            $resp = new ResponseResult();
            $resp->sendError(ResponseResultStatus::USER_TOKEN_EXPIRES, '未登录!');
            echo $resp->getContent();
        } else {
            $this->response->redirect($moduleConfig->operator->login->url);
        }
        $this->view->disable();
        return false;
    }

    public function initialize()
    {
        $this->operator->cookies = $this->cookies;

        $moduleConfig = $this->di->get('moduleConfig');

        $this->tag->setTitle($moduleConfig->application->id);

        $this->pageNavLimit = $moduleConfig->application->offsetExists('pageLimit') ? $moduleConfig->application->pageLimit : $this->pageNavLimit;

        //$this->view->setVar('opRoleList', AdminOp::roleList());
        $this->view->setVar('operator', $this->operator);
        $this->view->setVar('main_nav_type', '');
        $this->view->setVar('left_nav_type', '');
    }

    /**
     * 数据库操作异常
     * @param \Phalcon\Mvc\Model $model
     * @return bool
     */
    public function databaseErrorLog($model)
    {
        $error = '';
        foreach($model->getMessages() as $msg)
        {
            $error .= $msg . ',';
        }
        $this->di->get('logger')->error('数据库异常, GET:' . json_encode($_GET) . ', POST:' . json_encode($_POST) . ', error: ' . $error);
        return false;
    }

    /**
     * 设置主导航类型
     * @param $type
     */
    public function setMainNav($type) {
        $this->view->setVar('main_nav_type', $type);
    }

    /**
     * 设置左侧导航类型
     * @param $type
     */
    public function setLeftNav($type) {
        $this->view->setVar('left_nav_type', $type);
    }

    public function operatorLog($opId, $type, $content)
    {
        $log = new BackendOperatorLog();
        $log->operator_id = $opId;
        $log->log_type = $type;
        $log->log_content = $content;
        $clientInfo = [
            'ip' => Util::UserIp(),
            'userAgent' => $this->request->getUserAgent(),
            'headers' => Util::GetAllHeaders(),
        ];
        $log->log_client_info = json_encode($clientInfo);
        if(!$log->save())
        {
            $error = '';
            foreach($log->getMessages() as $msg)
            {
                $error .= $msg . ',';
            }
            $this->di->get('logger')->error('数据库异常,记录API请求日志出错, GET:' . json_encode($_GET) . ', POST:' . $this->request->getRawBody() . ', error: ' . $error);
        }
    }
    

}